package com.bobamrz.dao;

import java.util.List;
import java.util.Set;

import org.hibernate.Query;
import org.hibernate.Session;

import com.bobamrz.domain.DocAttributeType;
import com.bobamrz.domain.DocCatalog;
import com.bobamrz.domain.DocType;
import com.bobamrz.domain.DocTypeAttribute;
import com.bobamrz.domain.Document;
import com.bobamrz.hibernate.HibernateUtil;

public class DocTypeDAO implements IDocTypeDAO {
	
	//private Logger log = Logger.getLogger(DocumentDAO.class);
	
	private Session session = HibernateUtil.getSessionFactory().getCurrentSession();
	
	public List<DocType> getSuperDocTypesList() {
		String hql = "FROM DocType WHERE level=1";
		Query query = session.createQuery(hql);
		return query.list();
	}
	
	
	/* ---- CODE BELOW USED FOR VALIDATION --- */
		
	public DocType getDocTypeByDocumentId(long id) {
		DocumentDAO documentDAO = new DocumentDAO();
		Document doc = documentDAO.getById(id);
		DocType docType = doc.getDocumentDocType().getDocType();
		return docType;
	}
	
	public DocType getDocTypeByDocTypeName(String docTypeName) {
		String hql = "FROM DocType WHERE typeName='" + docTypeName + "'";
		Query query = session.createQuery(hql);
		return (DocType) query.list().get(0);
	}
	
	private DocAttributeTypeHome docAttributeTypeHome = new DocAttributeTypeHome();

	public boolean isAttributeRequired(String docTypeName, String verifiableAttrName) {
		String result = "";
		List<DocAttributeType> matchingAttributes = docAttributeTypeHome.findIdByName(verifiableAttrName);
		DocType docType = getDocTypeByDocTypeName(docTypeName);
		Set<DocTypeAttribute> documentAttributes = docType.getDocTypeAttributes();
		for(DocTypeAttribute documentAttribute : documentAttributes) {
			for(DocAttributeType attribute : matchingAttributes) {
				if(attribute.getDocAttributeType()==documentAttribute.getDocTypeAttribute()) {
					result = documentAttribute.getRequired();
				}
				
			}
		}
		if("Y".equals(result)) {
			return true;
		}
		return false;
	}
	
	public void save(DocType dt) {
		session.merge(dt);
	}
}